package m.jclecai.com.fragment.home;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;

import com.google.gson.Gson;
import com.squareup.okhttp.Request;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import m.jclecai.com.MyApplication;
import m.jclecai.com.R;
import m.jclecai.com.adapter.channel.MyChannelAdapter;
import m.jclecai.com.base.BaseFragment;
import m.jclecai.com.bean.home.HomeMenu;
import m.jclecai.com.bean.home.Sub;
import m.jclecai.com.bean.home.SubLists;
import m.jclecai.com.constant.Constant_Url;
import m.jclecai.com.contents.NotificationKey;
import m.jclecai.com.data.Lecai_SDK;
import m.jclecai.com.data.ReceivedData;
import m.jclecai.com.factory.FragmentFactory;
import m.jclecai.com.notification.NotificationCenter;
import m.jclecai.com.utils.ScreenUtils;
import m.jclecai.com.utils.http.HttpManager;
import m.jclecai.com.view.tabpagerindictor.TabPageIndicator;

/**
 * Created by andy on 2017/7/21.
 * <p>
 *  足球新闻开关也面
 */

public class HomeSwitchFragment extends BaseFragment implements View.OnClickListener{

    private String TAG = "HomeSwitchFragment";

    @BindView(R.id.id_viewpager)
    ViewPager viewPager;
    @BindView(R.id.ll_show)
    LinearLayout ll_show;
    /**
     *  防头条
     */
    @BindView(R.id.tab_indicator)
    TabPageIndicator indicator;
    @BindView(R.id.iv_ranking)
    LinearLayout iv_ranking;



    private BasePagerAdapter adapter;

    private int mPosition = 0;
    private List<Sub> titleList=new ArrayList<>();


    public void setPosition(int position) {
        mPosition = position;
    }



    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 12345678:
                    if (adapter == null) {
                        adapter = new BasePagerAdapter(getActivity().getSupportFragmentManager());
                        viewPager.setAdapter(adapter);
                    } else {
                        adapter.notifyDataSetChanged();
                    }
                    indicator.setViewPager(viewPager);
                    setTabPagerIndicator();
                    break;
            }
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.frament_home_switch;
    }

    @Override
    public void initData() {
        super.initData();
        setTitle("首页");
//        rightOptionText("开奖信息");
        iv_ranking.setOnClickListener(this);



    }




    /**
     * 请求数据；
     */
    public void requestData(String type) {
        Constant_Url.HTTP_URL = MyApplication.HTTP_URL_MENU;
//        showDialog();
        HttpManager.getAsyn(Constant_Url.MENNU_TITLE, new HttpManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
//                dissDialog();
                DisPlay("网络异常！！！");
            }

            @Override
            public void onResponse(String response) {
//                dissDialog();
                if(!TextUtils.isEmpty(response)){
                    Gson gson = new Gson();
                    ReceivedData.HomeMenusData homeMenusData =
                            gson.fromJson(response, ReceivedData.HomeMenusData.class);
                    Log.e(TAG,homeMenusData.data.getItems().toString());
                    List<HomeMenu> items = homeMenusData.data.getItems();
                    if (null!=items&&items.size()>0&&!items.equals("[]")){
                        if (null!=titleList&&titleList.size()>0){
                            titleList.clear();
                        }
                        for (int i = 0; i < items.size(); i++) {
                            List<SubLists> subItems = items.get(i).getSubItems();
                            for (int j = 0; j < subItems.size(); j++) {
                                Sub s= new Sub(subItems.get(j).getResourceId(),subItems.get(j).getName());
                                titleList.add(s);
                                if (j>2){
                                    break;
                                }
                            }

                        }
                        Message msg = new Message();
                        msg.what = 12345678;
                        handler.sendMessage(msg);
                    }

                }


            }

        });
    }


    /**
     *  初始化 tabIndicater
     */
    private void setTabPagerIndicator(){
        indicator.setIndicatorMode(TabPageIndicator.IndicatorMode.MODE_WEIGHT_NOEXPAND_SAME);// 设置模式，一定要先设置模式
        indicator.setDividerColor(Color.parseColor("#FFFFFF"));// 设置分割线的颜色
        indicator.setDividerPadding(ScreenUtils.dp2px(MyApplication.getInstance(), 20));
        indicator.setIndicatorColor(Color.parseColor("#FF7417"));// 设置底部导航线的颜色
        indicator.setTextColorSelected(getResources().getColor(R.color.color_select_color));// 设置tab标题选中的颜色
        indicator.setTextColor(getResources().getColor(R.color.color_99000000));// 设置tab标题未被选中的颜色
        indicator.setTextSize(ScreenUtils.dp2px(MyApplication.getInstance(), 17));// 设置字体大小
        indicator.setUnderlineColor(Color.parseColor("#FFFFFF"));
        indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                Log.e("--pospos--", position + "");
                Lecai_SDK.title_id = titleList.get(position).getResourceId();
                NotificationCenter.defaultCenter.postNotification(NotificationKey.FmLoadData);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View v) {
        showPop();
    }

    /**
     * tabIndicater 绑定数据
     */
    class BasePagerAdapter extends FragmentPagerAdapter {

        public BasePagerAdapter(FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int position) {
            return FragmentFactory.createForNews(titleList.get(position).getResourceId());
        }

        @Override
        public int getCount() {
            return titleList == null ? 0 : titleList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return titleList.get(position).getName();
        }

    }


    PopupWindow pop = null;
    MyChannelAdapter myChannelAdapter = null;
    /**
     *  添加我的频道
     */
    private void showPop() {
        if (pop == null) {
            LayoutInflater inflater = LayoutInflater.from(getContext());
            View popMenu = inflater.inflate(R.layout.layout_add_menus_type, null);
            pop = new PopupWindow(popMenu, WindowManager.LayoutParams.MATCH_PARENT,
                    WindowManager.LayoutParams.MATCH_PARENT, true);
            //设置SelectPicPopupWindow弹出窗体可点击
            pop.setFocusable(true);
            GridView gridView = popMenu.findViewById(R.id.gv_my_channel);
            gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
            myChannelAdapter = new MyChannelAdapter(getActivity(),titleList);
            gridView.setAdapter(myChannelAdapter);
            gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    viewPager.setCurrentItem(position);
                    pop.dismiss();
                }
            });


            popMenu.findViewById(R.id.iv_cancel).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    pop.dismiss();
                }
            });
        }
        pop.showAtLocation(ll_show, Gravity.BOTTOM,
                ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                pop.dismiss();
            }
        });
    }


}
